import { defineStore } from 'pinia'
import http from '@/utils/axios'
import API from '@/config/api'
import { ElMessage } from 'element-plus'

// 问题状态管理
export const useQuestionStore = defineStore('question', {
  state: () => ({
    recommendQuestions: [],  // 推荐问题列表
    latestQuestions: [],    // 最新问题列表
    loading: false,         // 加载状态
    currentQuestion: null   // 当前问题详情
  }),

  getters: {
    // 获取推荐问题列表
    getRecommendQuestions: (state) => state.recommendQuestions,
    // 获取最新问题列表
    getLatestQuestions: (state) => state.latestQuestions,
    // 获取当前问题详情
    getCurrentQuestion: (state) => state.currentQuestion
  },

  actions: {
    // 从URL中提取问题ID
    _extractQuestionId(url) {
      const parts = url.split('/')
      return parts[parts.length - 1]
    },

    // 获取问题详情
    async fetchQuestionDetail(questionId) {
      try {
        const response = await http.get(`/api/b1/aggregation/by_id/${questionId}`);
        this.currentQuestion = response.data;
      } catch (error) {
        console.error('获取问题详情失败:', error);
        ElMessage.error('获取问题详情失败');
      }
    },

    // 获取推荐问题列表
    async fetchRecommendQuestions() {
      try {
        this.loading = true
        const response = await http.get(API.GET_QUESTIONS)
        
        if (response.data) {
          // 解析问题列表
          const items = response.data.first?.items || []
          const questions = await Promise.all(
            items.map(url => this._fetchQuestionDetail(url))
          )
          
          // 过滤掉获取失败的问题
          this.recommendQuestions = questions.filter(q => q !== null)
        }
      } catch (error) {
        console.error('获取推荐问题列表失败:', error)
        ElMessage.error('获取推荐问题列表失败')
      } finally {
        this.loading = false
      }
    },

    // 获取最新问题列表
    async fetchLatestQuestions() {
      try {
        this.loading = true
        const response = await http.get(API.GET_QUESTIONS)
        
        if (response.data) {
          // 解析问题列表
          const items = response.data.first?.items || []
          const questions = await Promise.all(
            items.map(url => this._fetchQuestionDetail(url))
          )
          
          // 过滤掉获取失败的问题并按时间排序
          this.latestQuestions = questions
            .filter(q => q !== null)
            .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
        }
      } catch (error) {
        console.error('获取最新问题列表失败:', error)
        ElMessage.error('获取最新问题列表失败')
      } finally {
        this.loading = false
      }
    },

    // 发送问题
    async askQuestion(data) {
      try {
        const response = await http.post(API.ASK, data)
        
        if (response.data) {
          ElMessage.success('提问成功')
          // 刷新问题列表
          await this.fetchLatestQuestions()
          return true
        }
        return false
      } catch (error) {
        console.error('提问失败:', error)
        ElMessage.error('提问失败，请稍后重试')
        return false
      }
    },

    async fetchAnswerPosts(questionId) {
      try {
        const response = await http.get('/api/b1/aggregation/query', { params: { id: questionId, global: true } });
        const collectedPostUrl = response.data.pubpub.collectedPost;
        const postsResponse = await http.get(collectedPostUrl);
        const items = postsResponse.data.first.items || [];
        const answerContents = [];
        for (const itemUrl of items) {
          const postResponse = await http.get(itemUrl);
          answerContents.push(postResponse.data.content);
        }
        return answerContents;
      } catch (error) {
        console.error('获取回答帖子失败:', error);
        return [];
      }
    },

    async _fetchQuestionDetail(url) {
      try {
        // 将完整URL转换为相对路径
        const relativePath = url.replace('https://test1.pri1.b582u3ah.cn', '');
        const response = await http.get(relativePath);
        return {
          id: this._extractQuestionId(url),
          name: response.data.name,
          summary: response.data.summary,
          createdAt: response.data.published
        };
      } catch (error) {
        console.error('获取问题详情失败:', error);
        return null;
      }
    }
  }
}) 